<template>
  <div class="sheet-wrapper">
    <div class="clock-wrap" v-if="this.survey.type == 'exam'&&this.survey.autoStop==true">
      <div class="clock">
        距离结束时间:
        <div class="times">
          {{ this.formatTime() }}
        </div>
      </div>
    </div>
    <div class="reject-page" v-if="isClosed && onPreviewMode==false">
      <el-result icon="warning" title="问卷尚未开启" subTitle="请返回主页" v-if="survey.status == 0">
        <template slot="extra">
          <el-button type="primary" size="medium" @click="returnHome">返回</el-button>
        </template>
      </el-result>
      <el-result icon="danger" title="问卷停止收集" subTitle="请返回主页" v-else>
        <template slot="extra">
          <el-button type="primary" size="medium" @click="returnHome">返回</el-button>
        </template>
      </el-result>
    </div>
    <div class="sheet" v-else>
      <h4 class="form-name-text" style="text-align: center;">{{ survey.QName }}</h4>
      <div class="form-name-text" style="text-align: left;">{{ survey.Qdescription }}</div>
      <div class="el-divider"></div>
      <div>
        <!-- 此處是問題 -->
        <div v-for="(item,index) in shuffledArray" :key="index">
          <div class="qanswer">
            <span style="margin-top:6px;font-weight:bold;height:100%" v-if="showOrder()">{{ index + 1 }}.</span>
            <component :options="options" :leftNumber="res[index]" :is="itemTypeTransformer(item.type)"
              @change="handleNewAnswer($event,item.order)" :question="item" :ref="'ques' + index">
            </component>
          </div>
          <el-divider></el-divider>
        </div>
      </div>
      <button type="button" class="el-button el-button1"
        style="background-color: rgb(64, 158, 255); border-color: rgb(64, 158, 255);" @click="submitAnswer"
        v-show="onSaving==false&&onPreviewMode==false">
        <span>提交</span></button>
      <button type="button" class="el-button el-button2" v-show="false"
        style="background-color: rgb(64, 158, 255); border-color: rgb(64, 158, 255);">
        <span>保存</span></button>
    </div>
  </div>
</template>
<script>
import QitemCheckbox from "../components/Item/QitemCheckbox.vue";
import QitemLocation from "../components/Item/QitemLocation.vue";
import QitemRadio from "../components/Item/QitemRadio.vue";
import QitemRate from "../components/Item/QitemRate.vue";
import QitemTextBlank from "../components/Item/QitemTextBlank.vue";

export default {
  components: {
    QitemCheckbox,
    QitemRadio,
    QitemRate,
    QitemTextBlank,
    QitemLocation
  },
  name: "Answer",
  props: {
    QID64: {
      type: String,
      default: -1
    },
    onPreviewMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      options: {},
      onSaving: false,
      qid64: "LTE=",
      qid: -1,
      shuffle: false,
      isClosed: false,
      survey: {
        // 問卷
        Questions: []
      },
      res: [],
      sortKey: [],
      answerSheet: {
        // 答卷
        QID: 1,
        UID: "123",
        timeStamp: 12345678910,
        type: "normal",
        answers: []
      },
      ETime: "",
      endTime: null,
      timer: "",
      time: {
        day: "0",
        hour: "0",
        minute: "0",
        second: "0"
      }
    };
  },
  computed: {
    shuffledArray() {
      if (this.is_shuffled) return this.survey.Questions.sort(this.mySort);
      else return this.survey.Questions;
    }
  },
  methods: {
    mySort(a, b) {
      var aorder = a.order % this.sortKey.length;
      var border = b.order % this.sortKey.length;
      return this.sortKey[aorder] - this.sortKey[border];
    },
    initOptions() {
      this.answerSheet.type = this.survey.type;
      this.isClosed = this.survey.status == 1 ? false : true;
      this.is_shuffled = this.survey.is_shuffled;
      this.options = this.$mTool.initOptions(this.survey.type);
      if (this.survey.type == "sign") this.res = this.survey.res;
    },
    showOrder() {
      return this.survey.autoOrder == true;
    },
    toResult() {
      this.$router.replace("/Result/" + this.QID64 + "/" + this.survey.type);
    },
    returnHome() {
      this.$router.replace("/");
    },
    initAnswers() {
      for (let item of this.survey.Questions) {
        let arr = [];
        switch (item.type) {
          case "rate":
            arr.push(0);
            break;
          case "single":
            arr.push("");
            break;
          case "multi":
            arr.push("");
            break;
          case "blank":
            for (let iitem of item.options) arr.push("");
            break;
          case "location":
            arr.push("");
            break;
        }
        this.answerSheet.answers.push(arr);
      }
    },
    handleNewAnswer(newAns, order) {
      switch (newAns.type) {
        case "blank":
          // 对应空对应答案
          var { value, index } = newAns;
          this.answerSheet.answers[order][index] = value;
          break;
        case "multi":
          // 一次性替换所有选项
          this.answerSheet.answers[order] = newAns.value;
          break;
        case "rate":
          // 替换下标0处
          this.answerSheet.answers[order][0] = newAns.value;
          break;
        case "single":
          // 同上
          this.answerSheet.answers[order][0] = newAns.value;
          break;
        case "location":
          // 同上
          this.answerSheet.answers[order][0] = newAns.value;
          break;
      }
      console.log(this.answerSheet.answers);
    },
    checkAnswer() {
      // 检查必做题答题情况
      let length = this.shuffledArray.length;
      for (let index = 0; index < length; index++) {
        let name = "ques" + index;
        var qitem = this.$refs[name][0];
        if (qitem.checkAnswer() == false) {
          this.$message.warning("存在未完成必做题：" + qitem.question.title);
          return false;
        }
      }
      return true;
    },
    submitAnswer() {
      //提交問卷
      if (this.checkAnswer() == true) {
        this.answerSheet.QID = this.qid;
        this.answerSheet.UID = this.$store.state.userName;
        this.answerSheet.timeStamp = new Date().getTime();
        if (this.$store.state.isLogin == false)
          this.answerSheet.UID =
            this.answerSheet.UID + this.answerSheet.timeStamp;
        this.onSaving = true;
        this.answerSheet.answers.forEach(item => {
          if (item.length < 1) item.push("");
          console.log(item);
        });
        console.log(this.answerSheet);
        this.$serve
          .submitAnswer(this.answerSheet)
          .then(res => {
            console.log(res);
            if (res.data.success == 1) {
              this.$message.success("答卷提交成功");
              this.onSaving = false;
              this.toResult();
              // this.$router.replace(
              //   "/correctAnswer/" +
              //     this.answerSheet.QID +
              //     "/" +
              //     this.answerSheet.UID
              // );
            } else {
              this.$message.error("答卷提交失败");
              this.onSaving = false;
            }
          })
          .catch(err => {
            this.$message.error("答卷提交失败");
            this.onSaving = false;
          });
      }
    },
    getData() {
      // 此處修改
      this.$serve
        .getSurveyPage(this.qid)
        .then(res => {
          this.survey = res.data;
          this.initOptions();
          if (!this.isClosed) this.initAnswers();
          console.log(this.survey);
        })
        .catch(error => {
          console.log("answer", error);
          this.$message.error("加载问卷失败,请刷新重试");
        });
    },
    itemTypeTransformer(qtype) {
      return this.$mTool.itemTypeTransformer(qtype);
    },
    setTime() {
      let time_now = new Date();
      time_now = time_now.getTime();
      let time_distance = this.endTime - time_now;
      console.log(time_distance);
      if (time_distance >= 0) {
        this.time.day = Math.floor(time_distance / 86400000);
        time_distance -= this.time.day * 86400000;
        this.time.hour = Math.floor(time_distance / 3600000);
        time_distance -= this.time.hour * 3600000;
        this.time.minute = Math.floor(time_distance / 60000);
        time_distance -= this.time.minute * 60000;
        this.time.second = Math.floor(time_distance / 1000);

        if (this.time.hour < 10) this.time.hour = "0" + this.time.hour;
        if (this.time.minute < 10) this.time.minute = "0" + this.time.minute;
        if (this.time.second < 10) this.time.second = "0" + this.time.second;

        console.log(this.time);
      }
    },
    refreshTime() {
      this.timer = setInterval(this.setTime, 1000);
    },
    formatTime() {
      return (
        this.time.day +
        "天 " +
        this.time.hour +
        ":" +
        this.time.minute +
        ":" +
        this.time.second
      );
    },
    getETime() {
      this.$serve.getETime(this.qid).then(res => {
        this.ETime = res.data.ETime;
        this.ETime = this.ETime.replace(/-/g, "/");
        console.log(this.ETime);
        this.endTime = new Date(this.ETime);
        console.log(this.endTime);
        this.endTime = this.endTime.getTime();
      });
    }
  },
  mounted() {
    this.qid = this.$AES.decrypt(this.QID64);
    this.sortKey = this.$mTool.ipToKey(returnCitySN["cip"]);
    this.getData();
    this.getETime();
    this.refreshTime();
  },
  beforeDestroy() {
    clearInterval(this.timer);
  }
};
</script>

<style scoped>
.qanswer {
  display: flex;
}

.sheet-wrapper {
  width: 100%;
  overflow: hidden;
  transform-origin: top;
  overflow: hidden;
  /* margin-top:50px; */
}

.sheet {
  width: 70%;
  min-height: 500px;
  padding: 15px;
  padding-bottom: 70px;
  margin: 15px auto;
  background-color: rgba(229, 239, 247, 0.87);
  position: relative;
}

.form-name-text {
  padding: 6px 10px;
  border: 1px dashed transparent;
  line-height: 30px;
  margin: 0;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}

.el-divider {
  display: block;
  height: 1px;
  width: 100%;
  margin: 24px 0;
}

.el-button1 {
  width: 100px;
  position: absolute;
  right: 15px;
  bottom: 15px;
}

.el-button2 {
  width: 100px;
  position: absolute;
  right: 130px;
  bottom: 15px;
}

.clock-wrap {
  position: fixed;
  right: 20%;
  top: 5%;
  z-index: 999;
}
.clock {
  position: absolute;
  width: 260px;
  right: 0;
  top: 0;
}
.times {
  color: red;
}
</style>